import { useUserStore } from '@/stores/modules/user'
import { createRouter, createWebHistory } from 'vue-router'
import { staticRoutes } from './staticRoutes'
import { dynamicRoutes } from './dynamicRoutes'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...staticRoutes, ...dynamicRoutes],
})

/**
 * 路由守卫
 */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  document.title = String(to.meta?.title || '默认标题')

  const isPublic = Boolean(to.meta?.public)
  const isLoginPage = to.path === '/login'
  const isLoggedIn = userStore.isLogin
  const userRole = userStore.user?.role

  // ✅ 1. 公共页面直接放行
  if (isPublic) return next()

  // ✅ 2. 未登录时，强制跳转登录页（保留跳转目标）
  if (!isLoggedIn) return next({ path: '/login', query: { redirect: to.fullPath } })

  // ✅ 3. 登录后访问 login 页面，跳转首页
  if (isLoggedIn && isLoginPage) {
    return next('/home')
  }

  // ✅ 4. 权限判断（roles 是数组，userRole 必须在其中）
  const roles = to.meta?.roles as string[] | undefined
  if (roles?.length && (!userRole || !roles.includes(userRole))) {
    return next('/403')
  }

  // ✅ 5. 正常放行
  next()
})

export default router
